package com.feige.security;

import com.feige.constant.Constants;
import com.feige.result.AjaxResult;
import com.feige.utils.jwt.JwtUtils;
import com.feige.utils.redis.RedisUtils;
import com.feige.utils.http.ResponseUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登出业务类
 */
public class TokenLogoutHandler implements LogoutSuccessHandler {


    private RedisUtils redisUtils;


    public TokenLogoutHandler(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = request.getHeader(Constants.TOKEN_KEY);
        if (token != null) {
            //清空当前用户缓存中的权限数据
            String username = JwtUtils.getUsernameAndNumFromToken(token);
            redisUtils.del(Constants.LOGIN_USER_KEY + username);
            ResponseUtil.out(response, AjaxResult.success());
        }
        ResponseUtil.out(response, AjaxResult.error());
    }
}
